export interface WatermarkOptions {
  content: string;
  width?: number;
  height?: number;
  fontSize?: number;
  fontColor?: string;
  zIndex?: number;
  rotate?: number;
  gapX?: number;
  gapY?: number;
}

const defaultOptions = (): Partial<WatermarkOptions> => {
  const { width, height } = document.body.getBoundingClientRect();
  return {
    width: width,
    height: height,
    fontSize: 16,
    fontColor: '#999',
    zIndex: 999,
    rotate: -20,
    gapX: 100,
    gapY: 100,
  };
};

export const useWatermark = (options: WatermarkOptions) => {
  const [watermarkOptions, setWatermarkOptions] =
    useState<WatermarkOptions>(options);
  const opts = Object.assign({}, defaultOptions(), watermarkOptions);

  const updateWatermark = (newOptions: Partial<WatermarkOptions>) => {
    setWatermarkOptions((prev) => ({
      ...prev,
      ...newOptions,
    }));
  };

  useEffect(() => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    canvas.width = opts.gapX!;
    canvas.height = opts.gapY!;
    ctx.translate(canvas.width / 2, canvas.height / 2);
    ctx.rotate((opts.rotate! * Math.PI) / 180);
    ctx.font = `${opts.fontSize}px Arial`;
    ctx.fillStyle = opts.fontColor!;
    ctx.textAlign = 'center';
    ctx.globalAlpha = 0.15;

    ctx.fillText(opts.content!, 0, 0);

    const watermark = document.createElement('div');
    watermark.id = 'watermark';
    watermark.style.position = 'fixed';
    watermark.style.top = '0px';
    watermark.style.left = '0px';
    watermark.style.width = `${opts.width}px`;
    watermark.style.height = `${opts.height}px`;
    watermark.style.zIndex = `${opts.zIndex}`;
    watermark.style.pointerEvents = 'none';
    watermark.style.overflow = 'hidden';
    watermark.style.backgroundImage = `url(${canvas.toDataURL()}) `;
    watermark.style.backgroundSize = `${opts.gapX}px ${opts.gapY}px`;
    document.body.appendChild(watermark);
    return () => {
      document.body.removeChild(watermark);
    };
  }, [opts]);
  return [updateWatermark, opts] as const;
};
